package com.ray.auth.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ray.auth.common.CommonValue;
import com.ray.auth.system.emun.LinkType;
import com.ray.auth.system.emun.MenuType;
import com.ray.auth.system.emun.UseStatus;
import com.ray.auth.system.service.AppService;
import com.ray.auth.system.service.ButtonService;
import com.ray.auth.system.service.MenuService;
import com.ray.auth.system.service.RoleService;
import com.ray.auth.system.service.UserGroupService;
import com.ray.auth.system.table.customMapper.CustomMenuMapper;
import com.ray.auth.system.table.entity.App;
import com.ray.auth.system.table.entity.Menu;
import com.ray.auth.system.table.entity.MenuExample;
import com.ray.auth.system.table.entity.MenuExample.Criteria;
import com.ray.auth.system.table.entity.MenuRel;
import com.ray.auth.system.table.entity.MenuRelExample;
import com.ray.auth.system.table.mapper.MenuMapper;
import com.ray.auth.system.table.mapper.MenuRelMapper;
import com.ray.auth.system.vo.MenuParams;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.datastructure.TreeNode;
import com.zjhc.flyhong.common.function.enums.DeleteEnum;
import com.zjhc.flyhong.common.function.exception.BussinessException;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.function.validate.EntityValidate;
import com.zjhc.flyhong.common.function.validate.rule.FieldRule;
import com.zjhc.flyhong.common.function.validate.rule.RuleEnum;
import com.zjhc.flyhong.common.util.UUIDUtil;
import com.zjhc.flyhong.common.web.ErrorMsg;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.flyhong.common.web.ResultHelper;
import com.zjhc.flyhong.common.web.SuccessMsg;
import com.zjhc.flyhong.common.web.base.BaseService;
/**
 * <h1>系统权限应用  菜单  服务实现</h1>
 * @创建人 ray
 * @创建时间 2017-06-10
 * @版本 1.0
 * @重要修改备注 
 * 
 */
@Service
public class MenuServiceImpl extends BaseService implements MenuService {
	/**日志对象**/
	private static Logger logger = Logger.getLogger(MenuServiceImpl.class);
	/**************实现类  其他对象 引用  开始***********************/
	/**应用数据库操作对象**/
	@Autowired
	private MenuMapper menuMapper;
	/**应用数据库操作对象**/
	@Autowired
	private MenuRelMapper menuRelMapper;
	/**菜单关联数据库操作**/
	@Autowired
	private CustomMenuMapper customMenuMapper;
	/**用户组数据库操作**/
	@Autowired
	private UserGroupService userGroupService;
	/**角色数据库操作**/
	@Autowired
	private RoleService roleService;
	@Autowired
	private AppService appService;
	@Autowired
	private ButtonService buttonService;
	
	/**************实现类  其他对象 引用  结束***********************/
	/***
	 * @描述 <h1>添加菜单</h1><br/>数据库操作信息从  Operater对象中获取.
	 * @参数 entity 菜单对象
	 * @参数 operater 操作人信息
	 * @异常    内部捕获异常
	 * @事物    异常=>事物进行回滚
	 * @返回 result  返回结果  result.status => 0表示成功 ,其余表示失败
	 */
	@Transactional
	public Result<Object> saveMenu(Menu entity, LoginUser loginUser) {
		//对象验证 
		/*****************验证开始************************/	
		FieldRule fieldRule = new FieldRule();
		fieldRule.addRule(RuleEnum.IS_NOT_NULL, String.class, "menuName","菜单名称")
		.addRule(RuleEnum.IS_NOT_NULL, String.class, "url","请求路径")
		.addRule(RuleEnum.IS_NOT_NULL, String.class, "authUrl","权限路径");
		Result<Object> rs =	EntityValidate.validate(entity, fieldRule);
		if(!rs.codeSuccess())return rs;
		/******************验证结束*******************/
		entity.setTenantId(loginUser.getTenantId());
		entity.setMenuId(UUIDUtil.getUUID());
		entity.setIsDelete(DeleteEnum.USE.getValue());
		entity.setAppId(getAppId(entity.getParentMenuId()));
		this.setUserForAdd(entity, loginUser);
		//获取应用ID
		
		//执行成功数量	
		int exeCount = menuMapper.insertSelective(entity);
		if(exeCount != 1)return ResultHelper.getError();
		return ResultHelper.getSuccess();
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public String getAppId(String menuId) {
		Menu menu = menuMapper.selectByPrimaryKey(menuId);
		if(ObjectUtil.isNotNull(menu)){
		   return menu.getAppId();	
		}
		return menuId;
	}

	/**
	 * 获取用户资源下授权的 菜单  包括用户、用户组、角色
	 * @param userId 用户ID
	 * @return 菜单资源
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> queryUserMenus(String userId,String appid) {
		List<Menu> list = new ArrayList<Menu>();
		//获取用户下的menu资源
		list.addAll(this.queryMenusByLinkType(userId,appid,LinkType.USER));
		//获取用户所在的用户组
		List<String> userGroupIds = userGroupService.queryGroupsAllByUserId(userId);
		//获取用户组下所有meunu资源
		for(String userGroupId:userGroupIds){
			list.addAll(this.queryMenusByLinkType(userGroupId,appid,LinkType.USERGROUP));
		}
		//获取用户所在用户组的角色ID
		for(String userGroupId:userGroupIds){
			//获取用户组下的角色
			List<String> roleIds = roleService.queryRoleByUserGroupId(userGroupId);
			//获取角色下所有meunu资源
			for(String roleId:roleIds){
				list.addAll(this.queryMenusByLinkType(roleId,appid,LinkType.ROLE));
			}
		}
		//获取用户所拥有的角色
		List<String> roleIds = roleService.queryRoleByUserId(userId);
		//获取角色下所有meunu资源
		for(String roleId:roleIds){
			list.addAll(this.queryMenusByLinkType(roleId,appid,LinkType.ROLE));
		}
		return list;
	}
	/**
	 * 通过关联ID和关联类型 获取对应的菜单资源
	 * @param linkId 关联ID
	 * @param linkType 关联类型
	 * @return 菜单资源
	 */ 
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> queryMenusByLinkType(String linkId,String appId, LinkType linkType) {
	 return customMenuMapper.selectMenuByLink(linkId, appId,linkType.getType(), UseStatus.ON.getType(),DeleteEnum.USE.getValue());
	}
    /**
     * 获取系统所有菜单
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> querySuperUserMenus(String appId) {
		MenuExample example = new MenuExample();
		example.createCriteria().andIsDeleteEqualTo(DeleteEnum.USE.getValue())
		.andAppIdEqualTo(appId);
		return menuMapper.selectByExample(example);
	}
	 /**
     * 通过父节点获取 菜单资源
     * @param id 父节点
     * @param loginUser 登录用户
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<TreeNode> queryMenuListByParentId(String id,Integer level, LoginUser loginUser) {
		List<TreeNode> list = new ArrayList<TreeNode>();
		//为空时候 新增一个虚拟节点
		if(StrUtil.isBlank(id)){
			//TreeNode node = new TreeNode(CommonValue.treeTopId, CommonValue.treeTopName,1,false);
			List<App> apps = appService.queryUseAppList();
			TreeNode node = null;
			for(App app : apps){
				node = new TreeNode(app.getAppId(),app.getAppName(),level, false);
				node.setValue(app);
				list.add(node);
			}
		}else{
			list.addAll(queryMenu(id,level,loginUser));
		}
		return list;
	}
    /**
     * 查询当前id下的菜单
     * @param id
     * @param loginUser
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private List<TreeNode> queryMenu(String id, Integer level,LoginUser loginUser) {
		ArrayList<TreeNode> list = new ArrayList<TreeNode>();
		MenuExample example = new MenuExample();
		Criteria criteria = example.createCriteria();
		if(!loginUser.isSuperManager()){
			criteria.andTenantIdEqualTo(loginUser.getTenantId());
		}
		criteria.andParentMenuIdEqualTo(id)
		.andMenuStatusEqualTo(UseStatus.ON.getType())
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		example.setOrderByClause("INDEX_SORT ASC");
		List<Menu> menuList = menuMapper.selectByExample(example);
		TreeNode node = null;
		for(Menu menu : menuList){
			node = new TreeNode(menu.getMenuId(), menu.getMenuName(),level, false);
			node.setValue(menu);
			list.add(node);
		}
		return list;
	}
	/**
	 * 查询所有从菜单
	 * @param params 查询参数
	 * @param page 分页信息
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public PageDto<Menu> queryMenuList(Menu params, PageDto<Menu> page, LoginUser loginUser) {
		MenuExample example = new MenuExample();
		Criteria criteria =  example.createCriteria();
		if(!loginUser.isSuperManager()){
			criteria.andTenantIdEqualTo(loginUser.getTenantId());
		}
		if(StrUtil.isNotBlank(params.getParentMenuId())){
			criteria.andParentMenuIdEqualTo(params.getParentMenuId());
		}
		
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		this.setExamplePage(example, page);
		page.setTotal(menuMapper.countByExample(example));
		page.setRecords(menuMapper.selectByExample(example));
		return page;
	}

	/**
	 * 通过主键删除菜单数据
	 * @param id 主键
	 * @param loginUser 操作用户
	 * @return
	 */
	@Transactional
	public Result<Object> deleteMenu(String id, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		Menu record = new Menu();
		record.setMenuId(id);
		record.setIsDelete(DeleteEnum.DELETE.getValue());
		this.setUserForUpdate(record, loginUser);
		int opCount = menuMapper.updateByPrimaryKeySelective(record);
		if(opCount != 1){
			logger.error("MenuServiceImpl=>deleteMenu is error");
			throw new BussinessException(-1, ErrorMsg.DELETE_ERROR);
		}
		//删除下级菜单
		deleteNextMenu(id,loginUser);
		//删除菜单关联
		deleteMenuRel(id,loginUser);
		//删除按钮
		buttonService.deleteButtonByMenuId(id, loginUser);
		return result;
	}
	
	 /**
	  * 删除菜单关联
	  * @param id
	  * @param loginUser
	  */
	@Transactional
	 private void deleteMenuRel(String id, LoginUser loginUser) {
		    MenuRel record = new MenuRel();
			record.setIsDelete(DeleteEnum.DELETE.getValue());
			this.setUserForUpdate(record, loginUser);
			
			MenuRelExample example = new MenuRelExample();
			example.createCriteria().andMenuIdEqualTo(id);
			menuRelMapper.updateByExampleSelective(record, example);
	}
	 

	/**
	  * 删除下级菜单
	  * @param id
	  * @param loginUser
	  */
	@Transactional
	 private void deleteNextMenu(String id, LoginUser loginUser) {
		List<Menu> menus = this.queryAllChildMenuList(id, loginUser);
		for(Menu menu :menus){
			//删除下级
			deleteNextMenu(menu.getMenuId(), loginUser);
			//删除菜单关联
			deleteMenuRel(menu.getMenuId(),loginUser);
			//删除按钮
			buttonService.deleteButtonByMenuId(menu.getMenuId(), loginUser);
			//删除当前
			this.deleteMenu(menu.getMenuId(), loginUser);
		}
	}

	/**
     * 通过ID查询菜单信息
     * @param id 菜单编号
     * @param loginUser 登录用户
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Menu queryMenu(String id, LoginUser user) {
		return menuMapper.selectByPrimaryKey(id);
	}

	@Transactional
	public Result<Object> updateMenu(Menu record, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		this.setUserForUpdate(record, loginUser);
		int opCount = menuMapper.updateByPrimaryKeySelective(record);
		if(opCount != 1){
			logger.error("MenuServiceImpl=>menuUpdate is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	
	/**
     * 通过父节点id获取父节点信息 提供符节点ID 0 返回虚拟节点
     * @param patentMenuId
     * @param user
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Menu queryParentMenu(String patentMenuId, LoginUser user){
		if(StrUtil.equals(patentMenuId, CommonValue.treeTopId) || ObjectUtil.isNull(patentMenuId)){
			Menu menu = new Menu();
			menu.setMenuId(CommonValue.treeTopId);
			menu.setMenuName(CommonValue.treeTopName);
			return menu;
		}else{
			return queryMenu(patentMenuId, user);
		}
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<TreeNode> queryUserHomeMenu(String appid,LoginUser loginUser) {
		List<TreeNode> menus = new ArrayList<TreeNode>();
		//超级管理员直接获取全部
		if(loginUser.isSuperManager()){
			querySuperManagerMenus(menus,appid,loginUser);
		}else{
			queryUserMenus(menus,appid,loginUser);
		}
		return menus;
	}
    /**
     * 超级管理员首页菜单
     * @param menus
     * @param loginUser
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private void querySuperManagerMenus(List<TreeNode> menus, String parentMenuId,LoginUser loginUser) {
		TreeNode treeNode = null;
		List<Menu> list = querySuperUserMenusByParentMenuId(parentMenuId);
		for(Menu menu :list){
			treeNode = new TreeNode(menu.getMenuId(), menu.getMenuName(), 0, false);
			treeNode.setValue(menu);
			treeNode.setChildren(queryChildMenu(menu.getMenuId()));
			menus.add(treeNode);
		}
	}
	
	/**
     * 员工首页菜单
     * @param menus
     * @param loginUser
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private void queryUserMenus(List<TreeNode> menus, String parentMenuId,LoginUser loginUser) {
		TreeNode treeNode = null;
		List<Menu> list = queryUserMenusByParentMenuId(parentMenuId,loginUser.getUserId());
		for(Menu menu :list){
			treeNode = new TreeNode(menu.getMenuId(), menu.getMenuName(), 0, false);
			treeNode.setValue(menu);
			treeNode.setChildren(queryUserChildMenu(menu.getMenuId(),loginUser.getUserId()));
			menus.add(treeNode);
		}
	}
	/**
	 * 用户菜单
	 * @param parentMenuId
	 * @param userId
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	 private List<Menu> queryUserMenusByParentMenuId(String parentMenuId,String userId) {
		 if(StrUtil.isNotBlank(parentMenuId)){
			MenuExample example = new MenuExample();
			example.createCriteria().andIsDeleteEqualTo(DeleteEnum.USE.getValue())
			.andMenuStatusEqualTo(UseStatus.ON.getType())
			.andMenuTypeEqualTo(MenuType.MENU.getType())
			.andParentMenuIdEqualTo(parentMenuId);
			example.setOrderByClause("index_sort asc");
			MenuParams params = new MenuParams();
			params.setUserId(userId);
			params.setIsDelete(DeleteEnum.USE.getValue());
			params.setStatus(UseStatus.ON.getType());
			params.setRoleType(LinkType.ROLE.getType());
			params.setUserGroupType(LinkType.USERGROUP.getType());
			params.setUserType(LinkType.USER.getType());
			return customMenuMapper.selectMyMenu(example, params);
		}
		return new ArrayList<Menu>();
	}

	/**
	  * 获取子菜单
	  * @param menuId
	  * @return
	  */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	 private List<TreeNode> queryChildMenu(String menuId) {
		 List<TreeNode> menus = new ArrayList<TreeNode>();
		 TreeNode treeNode = null;
		 List<Menu> list = querySuperUserMenusByParentMenuId(menuId);
		 for(Menu menu :list){
			treeNode = new TreeNode(menu.getMenuId(), menu.getMenuName(), 0, false);
			treeNode.setValue(menu);
			treeNode.setChildren(queryChildMenu(menu.getMenuId()));
			menus.add(treeNode);
		 }
		 return menus;
	}
	 
	 /**
	  * 获取子菜单
	  * @param menuId
	  * @return
	  */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	 private List<TreeNode> queryUserChildMenu(String menuId,String userId) {
		 List<TreeNode> menus = new ArrayList<TreeNode>();
		 TreeNode treeNode = null;
		 List<Menu> list = queryUserMenusByParentMenuId(menuId,userId);
		 for(Menu menu :list){
			treeNode = new TreeNode(menu.getMenuId(), menu.getMenuName(), 0, false);
			treeNode.setValue(menu);
			treeNode.setChildren(queryChildMenu(menu.getMenuId()));
			menus.add(treeNode);
		 }
		 return menus;
	}

	/**
	  * 根据付菜单id获取
	  * @param parentMenuId 父菜单
	  * @return
	  */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> querySuperUserMenusByParentMenuId(String parentMenuId) {
		if(StrUtil.isNotBlank(parentMenuId)){
			MenuExample example = new MenuExample();
			example.createCriteria().andIsDeleteEqualTo(DeleteEnum.USE.getValue())
			.andMenuStatusEqualTo(UseStatus.ON.getType())
			.andMenuTypeEqualTo(MenuType.MENU.getType())
			.andParentMenuIdEqualTo(parentMenuId);
			example.setOrderByClause("index_sort asc");
			return menuMapper.selectByExample(example);
		}
		return new ArrayList<Menu>();
	}
	
	 /**
     * 更具类型查询
     * @param type
     * @param user
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> queryMenusByMenuType(String type, LoginUser user){
		Menu menu = new Menu();
		//超级管理员能查看所有
		if(!user.isSuperManager()){
			menu.setTenantId(user.getTenantId());
		}
		menu.setMenuStatus(UseStatus.ON.getType());
		menu.setIsDelete(DeleteEnum.USE.getValue());
		menu.setMenuType(type);
		return menuMapper.selectByRecord(menu);
	}
	/**
     * 查询拥有的资源
     * @param id
     * @param level
     * @param loginUser
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<TreeNode> queryMyMenuListByParentId(String id, Integer level, LoginUser loginUser){
		//管理员能查询到所有的资源
		if(loginUser.isSuperManager()){
			return queryMenuListByParentId(id, level, loginUser);
		}else{
			return queryMySelfMenuListByParentId(id, level, loginUser);
		}
	}
    /**
     * 获取自己的权限
     * @param id
     * @param level
     * @param loginUser
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private List<TreeNode> queryMySelfMenuListByParentId(String id, Integer level, LoginUser loginUser) {
		List<TreeNode> list = new ArrayList<TreeNode>();
		//为空时候 新增一个虚拟节点
		if(StrUtil.isBlank(id)){
			//TreeNode node = new TreeNode(CommonValue.treeTopId, CommonValue.treeTopName,1,false);
			//list.add(node);
			List<App> apps = appService.queryUseAppList();
			TreeNode node = null;
			for(App app : apps){
				node = new TreeNode(app.getAppId(),app.getAppName(),level, false);
				node.setValue(app);
				list.add(node);
			}
		}else{
			list.addAll(queryMyMenu(id,level,loginUser));
		}
		return list;
	}
    /**
     * 获取自己的菜单
     * @param id
     * @param level
     * @param loginUser
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private List<TreeNode> queryMyMenu(String id, Integer level, LoginUser loginUser) {
		ArrayList<TreeNode> list = new ArrayList<TreeNode>();
		MenuExample example = new MenuExample();
		example.createCriteria().andParentMenuIdEqualTo(id)
		//.andTenantIdEqualTo(loginUser.getTenantId())
		.andMenuStatusEqualTo(UseStatus.ON.getType())
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		MenuParams params  = new MenuParams();
		params.setUserId(loginUser.getUserId());
		example.setOrderByClause("INDEX_SORT ASC");
		List<Menu> menuList = customMenuMapper.selectMyMenu(example, params);
		TreeNode node = null;
		for(Menu menu : menuList){
			node = new TreeNode(menu.getMenuId(), menu.getMenuName(),level, false);
			node.setValue(menu);
			list.add(node);
		}
		
		return list;
	}
	/**
	 * 通过菜单id查询下级菜单
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> queryChildMenuList(String menuId, LoginUser user) {
		Menu params = new  Menu();
		params.setIsDelete(DeleteEnum.USE.getValue());
		params.setMenuStatus(UseStatus.ON.getType());
		params.setParentMenuId(menuId);
		return menuMapper.selectByRecord(params);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> queryAllChildMenuList(String menuId, LoginUser user) {
		Menu params = new  Menu();
		params.setIsDelete(DeleteEnum.USE.getValue());
		params.setParentMenuId(menuId);
		return menuMapper.selectByRecord(params);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> queryUserOnwerMenus(String userId, LoginUser loginUser) {
		MenuExample example = new MenuExample();
		example.createCriteria()
		//.andTenantIdEqualTo(loginUser.getTenantId())
		.andMenuStatusEqualTo(UseStatus.ON.getType())
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		MenuParams params  = new MenuParams();
		params.setUserId(userId);
		List<Menu> menuList = customMenuMapper.selectMyMenu(example, params);
		return menuList;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Menu> queryRoleOnwerMenus(String roleId, LoginUser user) {
		MenuExample example = new MenuExample();
		example.createCriteria()
		//.andTenantIdEqualTo(user.getTenantId())
		.andMenuStatusEqualTo(UseStatus.ON.getType())
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		MenuParams params  = new MenuParams();
		params.setRoleId(roleId);
		params.setIsDelete(DeleteEnum.USE.getValue());
		params.setRoleType(LinkType.ROLE.getType());
		params.setStatus(UseStatus.ON.getType());
		List<Menu> menuList = customMenuMapper.selectRoleMenu(example, params);
		return menuList;
	}
	
	 /**
     * 新增菜单关联
     * @param menuId
     * @param linkId
     * @param type
     * @param loginUser
     * @return
     */
	@Transactional
	public Result<Object> addMenuRel(String menuId, String linkId, String type, LoginUser loginUser){
		//对象验证 
		/*****************验证开始************************/	
		EntityValidate.isNotNull(menuId, "菜单编号");
		EntityValidate.isNotNull(linkId, "关联编号");
		EntityValidate.isNotNull(type, "关联类型");
		if(ObjectUtil.isNotNull(queryMenuRel(menuId, linkId, type, loginUser))){
			return ResultHelper.getError(-1,"关联已经存在.");
		}
		/******************验证结束*******************/
		MenuRel entity = new MenuRel();
		entity.setTenantId(loginUser.getTenantId());
		entity.setId(UUIDUtil.getUUID());
		entity.setIsDelete(DeleteEnum.USE.getValue());
		entity.setMenuId(menuId);
		entity.setLinkId(linkId);
		entity.setLinkType(type);
		this.setUserForAdd(entity, loginUser);
		//执行成功数量	
		int exeCount = menuRelMapper.insertSelective(entity);
		if(exeCount != 1)return ResultHelper.getError();
		return ResultHelper.getSuccess();
	}
    /**
     * 判断菜单关联
     * @param menuId
     * @param roleId
     * @param type
     * @param loginUser
     * @return
     */
	@Transactional
	public Result<Object> deleteMenuRel(String menuId, String linkId, String type, LoginUser loginUser){
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		MenuRel record = new MenuRel();
		record.setIsDelete(DeleteEnum.DELETE.getValue());
		this.setUserForUpdate(record, loginUser);
		MenuRelExample example = new MenuRelExample();
		example.createCriteria().andMenuIdEqualTo(menuId)
		.andLinkIdEqualTo(linkId).andLinkTypeEqualTo(type)
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		int opCount = menuRelMapper.updateByExampleSelective(record, example);
		if(opCount != 1){
			logger.error("MenuServiceImpl=>deleteMenuRel is error");
			throw new BussinessException(-1, ErrorMsg.DELETE_ERROR);
		}
		return result;
	}
	/**
     * 查询菜单关联
     * @param menuId
     * @param roleId
     * @param type
     * @param loginUser
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public MenuRel queryMenuRel(String menuId, String linkId, String type, LoginUser loginUser){
		MenuRel params = new MenuRel();
		params.setMenuId(menuId);
		params.setLinkId(linkId);
		params.setLinkType(type);
		params.setIsDelete(DeleteEnum.USE.getValue());
		List<MenuRel> list = menuRelMapper.selectByRecord(params);
		if(list == null || list.size() == 0){
			return null;
		}
		if(list.size() > 1){
		  logger.error("queryMenuRel> too maney reocrd to query.");
		  throw new BussinessException(-1, ErrorMsg.SYS_IN_ERROR);
		}
		return list.get(0);	
	}


}
